﻿using Reporting.Errorcode;
using Reporting.API.Application.Commands.SaleOrders;
using MediatR;
using AutoMapper;
using Reporting.Infrastructure.Interfaces.SaleOrders;
using Reporting.Errorcode.ErrorCode;

namespace Reporting.API.Application.CommandHandler.SaleOrders
{
    /// <summary>
    /// 删除 销售订单
    /// </summary>
    public class DeleteSaleOrderCommandHandler : IRequestHandler<DeleteSaleOrderCommand, ApiResult>
    {
        private readonly ISaleOrderRepository _saleOrderRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<DeleteSaleOrderCommandHandler> _logger;

        public DeleteSaleOrderCommandHandler(ILogger<DeleteSaleOrderCommandHandler> logger, IMapper mapper, ISaleOrderRepository saleOrderRepository)
        {
            _logger = logger;
            _mapper = mapper;
            _saleOrderRepository = saleOrderRepository;
        }

        public async Task<ApiResult> Handle(DeleteSaleOrderCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // id查询生产计划
                var productionPlans = await _saleOrderRepository.GetAsync(x => x.SaleOrderID == request.SaleOrderID);
                if (productionPlans == null)
                {
                    return ApiResult.Fail("删除失败，当前数据不存在", StatusCodeEnum.BadRequest);
                }
                // 删除生产计划
                var result = await _saleOrderRepository.DeleteAsync(productionPlans);
                return ApiResult.Success(StatusCodeEnum.Success);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除失败");
                throw;
            }
        }
    }
}
